<template>
  <div class="layout-good-spec">
    <div class="good-spec-list">
      <div class="good-spec-item" v-for="spec in specList" :key="spec.id">
        <div class="good-spec-label">
          <span>{{ spec.specName }}</span>
        </div>
        <div class="good-spec-value">
          <el-select
            v-model="specValue[spec.specCode]"
            placeholder="请选择"
            @visible-change="handleVisibleChange(spec.specCode)"
          >
            <el-option
              v-for="item in valueList[spec.specCode]"
              :key="item.rangeCode"
              :label="item.rangeValue"
              :value="item.rangeValue"
            ></el-option>
          </el-select>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getProductAttrRangeList } from "@/api/product";
export default {
  name: "GoodSpec",
  components: {},
  props: {
    specList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      list: [],
      specValue: {},
      valueList: {}
    };
  },
  watch: {
    specList() {
      this.init();
    }
  },
  created() {
    this.cache = {};
  },
  methods: {
    init() {
      this.specValue = {};
      this.valueList = {};
      const list = [];
      for (let item of this.specList) {
        list.push({
          specCode: item.specCode,
          specName: item.specName
        });
        this.$set(this.valueList, item.specCode, []);
        this.$set(this.specValue, item.specCode, item.specValue || '');
      }
      this.list = list;
    },
    handleVisibleChange(specCode) {
      this.getSpecValueList(specCode).then(list => {
        this.valueList[specCode] = list;
      });
    },
    getSpecValueList(specCode) {
      if (!this.cache[specCode]) {
        this.cache[specCode] = getProductAttrRangeList(specCode).then(res => {
          if (res.code === 200) {
            return res.data;
          } else {
            this.cache[specCode] = null;
            return [];
          }
        });
      }
      return this.cache[specCode];
    },
    getData() {
      const data = this.list.map(item => {
        return {
          ...item,
          specValue: this.specValue[item.specCode]
        };
      });
      console.log(data,9999)
      return data;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.layout-good-spec {
  .good-spec-list {
    .good-spec-item {
      margin-bottom: 12px;
      display: flex;
      .good-spec-label {
        width: 80px;
        text-align: right;
        margin-right: 12px;
      }
      .good-spec-value {
        width: 260px;
        .el-select {
          width: 100%;
        }
      }
    }
  }
}
</style>
